package com.tuyue.controller;

import com.tuyue.domain.User;
import com.tuyue.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Author: 王金海
 * @Description:
 * @Date: Created by Administrator on 2017/12/20.
 * @Modified By:
 */
@Controller
@RequestMapping("users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户管理
     * @param model
     * @return
     */
    @GetMapping
    public ModelAndView list(Model model){
        model.addAttribute("userList",userService.list());
        model.addAttribute("title","用户管理");
        return new ModelAndView("users/list","userModel",model);
    }

    /**
     * 根据ID获取用户信息
     * @param id
     * @param model
     * @return
     */
    @GetMapping("{id}")
    public ModelAndView view(@PathVariable("id") Long id, Model model){
        model.addAttribute("user",userService.findById(id));
        model.addAttribute("title","查看用户");
        return new ModelAndView("users/view","userModel",model);
    }

    @GetMapping("form")
    public ModelAndView form( Model model){
        model.addAttribute("user",new User());
        model.addAttribute("title","增加用户");
        return new ModelAndView("users/form","userModel",model);
    }

    @GetMapping("del/{id}")
    public ModelAndView del(@PathVariable("id") Long id){
        userService.del(id);
        return new ModelAndView("redirect:/users");
    }

    @PostMapping
    public ModelAndView addOrUpdata(User user){
        user= userService.addOrUpdata(user);
        return new ModelAndView("redirect:users");
    }

    @GetMapping("goUpdata/{id}")
    public ModelAndView goUpdata(@PathVariable("id") Long id,Model model){
        model.addAttribute("user",userService.findById(id));
        model.addAttribute("title","修改用户");
        return new ModelAndView("users/form","userModel",model);
    }
}
